package com.wft.design.oauth.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.wft.design.oauth.entity.OauthClient;
import com.wft.design.oauth.entity.OauthGrantCode;
import com.wft.design.oauth.service.GrantCodeService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author WFT
 * @date 2019/12/22
 * description: 基于Redis的授权码CRUD
 */
@Service
@RequiredArgsConstructor
public class GrantCodeServiceImpl implements GrantCodeService {

    private final RedisTemplate<String, OauthGrantCode> redisTemplate;

    /**
     * 缓存名称
     */
    private final static String CACHE_NAME = "oauth2:grant:code:%s";

    /**
     * 授权码有效期为15分钟
     */
    private final static long CODE_VALIDITY = 1000 * 60 * 15;

    @Override
    public OauthGrantCode selectById(String id) {
        String cacheKey = String.format(CACHE_NAME,id);
        OauthGrantCode grantCode = this.redisTemplate.opsForValue().get(cacheKey);
        //  删除授权码
        this.redisTemplate.delete(cacheKey);
        return grantCode;
    }

    @Override
    public Long createGrantCode(Long accountId, OauthClient client) {
        //  生成授权码
        long code = IdWorker.getId();
        //  创建授权码对象
        OauthGrantCode grantCode = new OauthGrantCode(accountId, client);
        grantCode.setId(code);
        //  保存保存到缓存中
        String key = String.format(CACHE_NAME,code);
        this.redisTemplate.opsForValue().set(key,grantCode,CODE_VALIDITY, TimeUnit.MILLISECONDS);
        return code;
    }


}
